import React, { useState } from "react";
// import { StateProps } from "./Todo";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../store/reducer";
import { addAction } from "../store/action";

export interface IProps {
  id: number;
  text: string;
  isFinished: boolean; //是否已完成
}

const TodoInput = () => {
  //3、输入框的状态
  const [text, setText] = useState("");

  //2、对输入框的值进行数据绑定
  const changeTextHandler = (e: React.ChangeEvent) => {
    //参数“e”隐式具有“any”类型  *声明为react的change对象
    // setText((e.target as HTMLInputElement).value); //类型“EventTarget & Element”上不存在属性“value”   *只有表单有value

    setText((e.target as HTMLInputElement).value);
  };

  const dispatch = useDispatch();
  const state = useSelector((state: RootState) => state);

  //1、取出输入框里面的值
  const addTodoHandler = () => {
    console.log(text);

    const data = [
      ...state,
      {
        id: new Date().getTime(),
        text: text,
        isFinished: false,
      },
    ];
    window.localStorage.setItem("data", JSON.stringify(data));

    console.log(data);

    //调用dispatch函数

    dispatch(
      addAction({
        id: new Date().getTime(),
        text: text,
        isFinished: false,
      })
    );
    //添加之后，清空输入框
    setText("");
  };

  return (
    <div className="todo-input">
      <input
        type="text"
        placeholder="请输入代办事项"
        onChange={changeTextHandler}
        value={text}
      ></input>
      <button onClick={addTodoHandler}>添加</button>
    </div>
  );
};

export default TodoInput;
